package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"choujiang/common/utils"
	"choujiang/box_server/service"
	"choujiang/common/models"
	"choujiang/common/consts"
)

func OrderAdd(c *gin.Context) {
	form := c.Request.Form
	Gid := form.Get("goods_id")
	Gnum := form.Get("goods_num")
	uniqueId := form.Get("uniqueId")
	realName := form.Get("realname")
	phone := form.Get("phone")
	address := form.Get("address")
	int64Gid, _ := strconv.ParseInt(Gid, 10, 64)
	int64Gnum, _ := strconv.ParseInt(Gnum, 10, 64)

	goods := model.GetGoodsById(int64Gid)
	if goods != nil {
		if goods.Type == 1 { //下单实物商品
			errType := service.CreateNewOrder(int64Gid, int64Gnum, uniqueId, realName, phone, address)
			if errType != nil {
				utils.Error(errType, c)
				return
			}
		} else { //兑换红包
			errType := service.ExchangePackage(int64Gnum, uniqueId, goods)
			if errType != nil {
				utils.Error(errType, c)
				return
			}
		}
	}

	utils.JSON("ok", c)
}

/**
 @description 获取用户的订单列表
 @return []model.orders
 @author guxiang
 @version v1 2018-11-26
 */
func OrderList(c *gin.Context) {
	form := c.Request.Form
	uniqueId := form.Get("uniqueId")
	user := model.GetUserByUniqueId(uniqueId)
	if user == nil {
		utils.Error(consts.ErrUserNotFound, c)
		return
	}
	orders := service.GetUserOrders(user)
	utils.JSON(orders, c)
}
